#!/bin/bash

YARN_CACHE=".yarn-test-cache"
TEST_DIR="_test-node-install"
OWD=$(pwd)

print_status() {
    echo
    echo "## $1"
    echo
}

cleanup() {
    print_status "Cleaning up ..."
    cd "${OWD}"
    exec_cmd "rm -rf ${TEST_DIR}"
}

bail() {
    echo 'Error executing command'
    cleanup
    exit 1
}

exec_cmd_nobail() {
    echo "+ $1"
    bash -c "$1"
}

exec_cmd() {
    exec_cmd_nobail "$1" || bail
}

print_status "Testing Node.js and Yarn installation ..."

exec_cmd "mkdir -p ${TEST_DIR} && cd ${TEST_DIR}"

# because the previous cd was in a subshell and only for show
cd $TEST_DIR

print_status "Creating test package ..."

cat > server.js << EOF
  const http = require('http')
      , bl   = require('bl')

  http.createServer(function (req, res) {
    req.pipe(bl(function (err, data) {
      res.setHeader('content-type', 'text/plain')
      if (err) {
        res.statusCode = 500
        res.end(err.stack)
      } else {
        res.statusCode = 200
        b = new Buffer.from(data.slice())
        res.end(b.reverse())
      }
      setTimeout(function () {
        process.exit(0)
      }, 200)
    }))
  }).listen(3456)
EOF

cat > test.js << EOF
  const hyperquest = require('hyperquest')
      , crypto     = require('crypto')
      , bl         = require('bl')
      , assert     = require('assert')
      , rnd        = [ crypto.randomBytes(32), crypto.randomBytes(32) ]

  function run () {
    var req = hyperquest.post('http://localhost:3456')

    req.pipe(bl(function (err, data) {
      assert.ifError(err)

      var rev     = data.toString('hex')
        , orig    = Buffer.concat(rnd)
        , i       = orig.length - 1
        , origRev = new Buffer.alloc(orig.length)

      for (; i >= 0; i--)
        origRev[orig.length - i - 1] = orig[i]

      assert.equal(rev, origRev.toString('hex'))

      console.log('SUCCESS')
    }))

    req.write(rnd[0])
    req.end(rnd[1])
  }

  setTimeout(run, 500)
EOF

cat > package.json << EOF
  {
    "name": "test",
    "version": "1.0.0",
    "main": "server.js",
    "dependencies": {
      "bl": "~0.9.1",
      "hyperquest": "~0.3.0"
    },
    "scripts": {
      "test": "yarn start; node test.js",
      "start": "node server.js &"
    }
  }
EOF

print_status "Installing dependencies ..."

exec_cmd "yarn install --cache-folder ${YARN_CACHE}"

print_status "Running test ..."

exec_cmd "yarn test"

cleanup
